package product;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.LineBorder;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Login extends JInternalFrame {

	Admin ad = null;
	SetLogin lg = null;
	String filename = null;

	String person_num = null;
	String person_name = null;
	String start_date = null;


	// DB 연동을 위한 아이들 
	Connection conn = null;
	String driver = "oracle.jdbc.driver.OracleDriver";
	String ip = "192.168.10.4";
	String ip_plus = ":1521:xe";

	String url = "jdbc:oracle:thin:@";

	String db_user = "hr";
	String db_pwd = "hr";


	ProductMain1 m; // 우리조 메인 프레임

	private JPanel panel;
	private JLabel lblNewLabel;
	private JPanel panel_1;
	private JPanel panel_3;
	private JPanel panel_4;
	private JLabel lblNewLabel_2;
	private JPanel panel_6;
	private JButton btnNewButton;
	private JPanel panel_7;
	private JPanel panel_8;
	private JLabel lblNewLabel_4;
	private JTextField userid;
	private JPanel panel_9;
	JPanel panel_10;
	private JLabel lblNewLabel_5;
	private JTextField userpw;


	public Login() {
		super("급여 관리 프로그램", true, true, true, true);
		getContentPane().setBackground(new Color(0, 0, 102));

		addInternalFrameListener(new InternalFrameAdapter() {
			@Override
			public void internalFrameClosed(InternalFrameEvent e) {

				// 전체 패널 지웠다가 다시 초기값.

				panel_10.removeAll();
				panel_10.setLayout(new BorderLayout(0, 0));
				panel_10.add(getPanel_1(), BorderLayout.NORTH);
				panel_10.add(getPanel_1_2(), BorderLayout.CENTER);
				panel_10.updateUI();

				// 로그인하면서 썼던 패널 부분 지웠다가 초기값 셋팅 

				panel_4.removeAll();
				panel_4.setLayout(new BorderLayout(0, 0));
				panel_4.add(getPanel_6(), BorderLayout.SOUTH);
				panel_4.add(getPanel_7(), BorderLayout.CENTER);
				panel_4.updateUI();

				// 제목 수정
				setTitle("급여 관리 프로그램");

				userid.setText("");
				userpw.setText("");

				userid.requestFocus(); // 커서를 userid 텍스트필드에 둔다.

				m.login = null; // 강제로 넌 널. 꺼져 

			}
			@Override
			public void internalFrameClosing(InternalFrameEvent e) {
				try {
					if(conn!=null) conn.close();
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		});
		setBounds(100, 100, 548, 377);
		getContentPane().setLayout(new BorderLayout(0, 0));
		getContentPane().add(getPanel_10(), BorderLayout.CENTER);

		connectDB();

	}

	public void getMain(ProductMain1 main){
		this.m = main;
	}

	// 전체 패널 
	private JPanel getPanel_10() {
		if (panel_10 == null) {
			panel_10 = new JPanel();
			panel_10.setBackground(new Color(0, 0, 102));
			panel_10.setLayout(new BorderLayout(0, 0));
			panel_10.add(getPanel_1(), BorderLayout.NORTH);
			panel_10.add(getPanel_1_2(), BorderLayout.CENTER);
		}
		return panel_10;
	}

	public void connectDB(){

		try {
			// 1) 드라이버 로딩

			Class.forName(driver).newInstance();

			// 2) Connection 객체 생성.
			url = url + ip + ip_plus;
			conn = DriverManager.getConnection(url, db_user, db_pwd);

			SalarySQL cd = new SalarySQL(conn);
			cd.salary(); //salary테이블에 값 입력
			cd.profit(); //profit테이블에 값 입력

		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void setData (String num, String name, String date){
		this.person_num = num;
		this.person_name = name;
		this.start_date = date;
	}

	public String[] getData (){

		String[] args = new String[3];

		args[0] = this.person_num;
		args[1] = this.person_name;
		args[2] = this.start_date;

		return args;
	}

	public void login(){

		// 텍스트필드에 모든 값이 입력됐으면

		if(!userid.getText().equals("") && !userpw.getText().equals("")){ // 맵에 저장된 데이터를 Collection으로 반환   

			try{
				String sql = "select * from memberdata where memberid = ?";

				PreparedStatement pstmt;
				pstmt = conn.prepareStatement(sql);

				pstmt.setString(1, userid.getText());
				//pstmt.setString(2, userpw.getText());

				ResultSet rs = pstmt.executeQuery(); // select

				if(rs.next()){
					// 관리자이면, level = 1. 그 외 사원은 level = 2

					if(rs.getString("memberid").equals("AZ")){ // 아이디가 관리자 아이디이다. 
						if (rs.getString("pwd").equals(userpw.getText())) // 비밀번호 검사
							successLogin(pstmt, rs, 1); // 관리자

						else{ // 비밀번호 잘못 입력했을 경우
							JOptionPane.showMessageDialog(null, 
									"비밀번호가 올바르지 않습니다.", "Error",
									JOptionPane.ERROR_MESSAGE);
							
							userpw.setText("");
							userpw.requestFocus();
						}
					}

					else{ // 아이디가 일반 사원이다. 
						if (rs.getString("pwd").equals(userpw.getText())) // 비밀번호 검사
							successLogin(pstmt, rs, 2); // 그 외 사원

						else{ // 비밀번호 잘못 입력했을 경우
							JOptionPane.showMessageDialog(null, 
									"비밀번호가 올바르지 않습니다.", "Error",
									JOptionPane.ERROR_MESSAGE);
							
							userpw.setText("");
							userpw.requestFocus();
						}
					}

				} // 데이터베이스에 해당 데이터가 존재할 경우.

				else{
					JOptionPane.showMessageDialog(null, 
							"귀하의 데이터가 존재하지 않습니다.", "Error",
							JOptionPane.ERROR_MESSAGE);
				}
			}
			catch(Exception ex){}
		}
		else{ // 텍스트 필드에 입력을 안했을 경우
			JOptionPane.showMessageDialog(null, 
					"사번과 패스워드를 입력해주세요.", "Error",
					JOptionPane.ERROR_MESSAGE);
		}

	}

	public void successLogin(PreparedStatement pstmt, ResultSet rs, int level) throws SQLException{

		// 올바른 로그인 진행 프로세스
		
		lg = new SetLogin(level, this); // SetLogin 객체 생성

		panel_4.removeAll(); // 패널의 컴포넌트를 모두 지워주고 
		panel_4.add(lg); // 패널 붙여주기
		panel_4.updateUI(); // 패널 업데이트 

		lg.setLabel(rs.getString("irum")+"님이 로그인 하였습니다.");

		// 로그인한 유저의 사번, 이름, 입사일 저장.
		setData(rs.getString("memberid"), rs.getString("irum"), rs.getString("hiredate"));

		// 다썼으니깐, 닫자
		rs.close();
		pstmt.close();
	}

	private JPanel getPanel_1() {
		if (panel == null) {
			panel = new JPanel();
			FlowLayout flowLayout = (FlowLayout) panel.getLayout();
			flowLayout.setVgap(20);
			panel.setBackground(new Color(0, 0, 102));
			panel.add(getLblNewLabel());
		}
		return panel;
	}
	private JLabel getLblNewLabel() {
		if (lblNewLabel == null) {
			URL url = getClass().getClassLoader().getResource("title2.png");
			Image img = Toolkit.getDefaultToolkit().getImage(url);
			lblNewLabel = new JLabel(new ImageIcon(img));
		}
		return lblNewLabel;
	}
	private JPanel getPanel_1_2() {
		if (panel_1 == null) {
			panel_1 = new JPanel();
			panel_1.setBackground(new Color(0, 0, 102));
			panel_1.setLayout(new BorderLayout(0, 0));
			panel_1.add(getPanel_3_1(), BorderLayout.SOUTH);
			panel_1.add(getPanel_4_1(), BorderLayout.CENTER);
		}
		return panel_1;
	}
	private JPanel getPanel_3_1() {
		if (panel_3 == null) {
			panel_3 = new JPanel();
			panel_3.setBackground(new Color(0, 0, 102));
			panel_3.add(getLblNewLabel_2());
		}
		return panel_3;
	}
	private JPanel getPanel_4_1() {
		if (panel_4 == null) {
			panel_4 = new JPanel();
			panel_4.setBackground(new Color(0, 0, 102));
			panel_4.setLayout(new BorderLayout(0, 0));
			panel_4.add(getPanel_6(), BorderLayout.SOUTH);
			panel_4.add(getPanel_7(), BorderLayout.CENTER);
		}
		return panel_4;
	}
	private JLabel getLblNewLabel_2() {
		if (lblNewLabel_2 == null) {
			lblNewLabel_2 = new JLabel(" ");
		}
		return lblNewLabel_2;
	}
	private JPanel getPanel_6() {
		if (panel_6 == null) {
			panel_6 = new JPanel();
			panel_6.setBorder(null);
			panel_6.setBackground(new Color(0, 0, 102));
			FlowLayout flowLayout = (FlowLayout) panel_6.getLayout();
			flowLayout.setVgap(20);
			panel_6.add(getBtnNewButton());
		}
		return panel_6;
	}
	private JButton getBtnNewButton() {
		if (btnNewButton == null) {
			URL url = getClass().getClassLoader().getResource("login.png");
			Image img = Toolkit.getDefaultToolkit().getImage(url);
			btnNewButton = new JButton(new ImageIcon(img));
			btnNewButton.setContentAreaFilled(false);
			btnNewButton.setBackground(new Color(0, 0, 102));
			btnNewButton.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					login();
				}
			});
			btnNewButton.setBorder(null);
		}
		return btnNewButton;
	}
	private JPanel getPanel_7() {
		if (panel_7 == null) {
			panel_7 = new JPanel();
			panel_7.setBackground(new Color(0, 0, 102));
			panel_7.setLayout(new GridLayout(0, 1, 0, 0));
			panel_7.add(getPanel_8());
			panel_7.add(getPanel_9());
		}
		return panel_7;
	}
	private JPanel getPanel_8() {
		if (panel_8 == null) {
			panel_8 = new JPanel();
			panel_8.setBackground(new Color(0, 0, 102));
			FlowLayout flowLayout = (FlowLayout) panel_8.getLayout();
			flowLayout.setHgap(10);
			flowLayout.setVgap(50);
			panel_8.add(getLblNewLabel_4());
			panel_8.add(getUserid());
		}
		return panel_8;
	}
	private JLabel getLblNewLabel_4() {
		if (lblNewLabel_4 == null) {
			lblNewLabel_4 = new JLabel("ID");
			lblNewLabel_4.setFont(new Font("Roboto", Font.PLAIN, 11));
			lblNewLabel_4.setForeground(new Color(255, 255, 255));
		}
		return lblNewLabel_4;
	}
	private JTextField getUserid() {
		if (userid == null) {
			userid = new JTextField();
			userid.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					
					if (Character.isLowerCase(e.getKeyChar())){ // 소문자이면 대문자로 변경
						
						// 방금 입력한 문자가 소문자이면, 그 해당 문자만 대문자로 변경해서 다시 셋팅
						userid.setText(userid.getText().replace(e.getKeyChar(), Character.toUpperCase(e.getKeyChar())));
					}
					
					if(e.getKeyCode() == KeyEvent.VK_ENTER){
						login();
					}
				}
			});
			userid.setFont(new Font("나눔고딕", Font.PLAIN, 11));
			userid.setBorder(new LineBorder(new Color(0, 0, 0), 2));
			userid.setColumns(10);
		}
		return userid;
	}
	private JPanel getPanel_9() {
		if (panel_9 == null) {
			panel_9 = new JPanel();
			panel_9.setBorder(null);
			panel_9.setBackground(new Color(0, 0, 102));
			FlowLayout flowLayout = (FlowLayout) panel_9.getLayout();
			flowLayout.setVgap(15);
			panel_9.add(getLblNewLabel_5());
			panel_9.add(getUserpw());
		}
		return panel_9;
	}
	private JLabel getLblNewLabel_5() {
		if (lblNewLabel_5 == null) {
			lblNewLabel_5 = new JLabel("PW");
			lblNewLabel_5.setFont(new Font("Roboto", Font.PLAIN, 11));
			lblNewLabel_5.setForeground(new Color(255, 255, 255));
		}
		return lblNewLabel_5;
	}
	
	private JTextField getUserpw() {
		if (userpw == null) {
			userpw = new JPasswordField(); // 비밀번호 입력시, '*'로 표시
			userpw.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent e) {
					if(e.getKeyCode() == KeyEvent.VK_ENTER){
						login();
					}
				}
			});
			userpw.setFont(new Font("나눔고딕", Font.PLAIN, 11));
			userpw.setBorder(new LineBorder(new Color(0, 0, 0), 2));
			userpw.setColumns(10);
		}
		return userpw;
	}
}
